package io.yunho.yunho.interview.two.java8.webflux.routerfunction;

import io.yunho.yunho.interview.two.java8.webflux.holedemo.User;
import io.yunho.yunho.interview.two.java8.webflux.holedemo.UserRepository;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * @author: yunho
 * @date: 2021/5/13 14:38
 * @description:
 */
@Component
public class UserHandler {

    private final UserRepository userRepository;

    public UserHandler(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    /**
     * 得到所有用户
     * @param var1
     * @return
     */
    Mono<ServerResponse> getAllUserHandle(ServerRequest var1){
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(this.userRepository.findAll(), User.class);
    }

    /**
     * 新增用户
     * @param var1
     * @return
     */
    Mono<ServerResponse> putUserHandle(ServerRequest var1){
        Mono<User> user = var1.bodyToMono(User.class);
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                //save方法不支持Mono对象，因此需要调用saveAll方法，该方法可以传入Publisher对象，而mono和flux都是Publisher对象
                .body(this.userRepository.saveAll(user), User.class);
    }

    /**
     * 根据ID删除用户
     * @param var1
     * @return
     */
    Mono<ServerResponse> deleteUserHandle(ServerRequest var1){
        String id = var1.pathVariable("id");
        return this.userRepository.findById(id)
                .flatMap(u -> this.userRepository.delete(u)
                        .then(ServerResponse.ok().build()))
                        //原先使用的defaultIfEmpty 这里不能用
                        .switchIfEmpty(ServerResponse.notFound().build());
    }
}
